<?php 

class Log_Model_Logger {
	
	const DB_PRIORITY = Zend_Log::NOTICE;

	const EMAIL_PRIORITY = Zend_Log::CRIT; 
	
	public function init () {
		$dp = Zend_Db_Table_Abstract::getDefaultAdapter();
		$db_writer = new Zend_Log_Writer_Db($dp,'log_message');
		
		$file=APPLICATION_PATH."/modules/log/settings/log.ini";
		$values = new Zend_Config_Ini($file);
		$settings = $values->toArray();
		
		$mail = new Zend_Mail();
		if (isset($settings['email']) && $settings['email'] ) {
			$mail->addTo($settings['email']);
		}
		$email_writer = new Zend_Log_Writer_Mail($mail);
		
		$db_priority = (isset($settings['db_priority']) && $settings['db_priority'] ) ? $settings['db_priority'] : self::DB_PRIORITY;
		$db_writer->addFilter(new Zend_Log_Filter_Priority((int)$db_priority));
		
		$email_priority = (isset($settings['email_priority']) && $settings['email_priority'] ) ? $settings['email_priority'] : self::EMAIL_PRIORITY;
		$email_writer->addFilter(new Zend_Log_Filter_Priority((int)$email_priority));
		
		$logger = new Zend_Log();
		$logger->setTimestampFormat('Y-m-d H:i:s');
		$logger->addWriter($db_writer)->addWriter($email_writer);
		
		Zend_Registry::set ( 'log', $logger );
		self::log('Запуск приложения', Zend_Log::INFO);
	}
	
	public static function log ($message, $priority, $extras = array()) {
		if(! Zend_Registry::get('cnf')->installed==true) return false;
		if (Zend_Registry::isRegistered('log')) {
			$user = null;
			if (Zen_Client::isLoged()) {
				$user = Zen_Client::getCurrent();
			} elseif (Zen_User::isLoged()) {
				$user = Zen_User::getCurrent();
			}
			if ($user) {
				$extras['username'] = $user->name;
			}
			$logger = Zend_Registry::get('log');
			$logger->log($message, $priority, $extras);
		}
	}
	
}